import { parse } from 'querystring';
import { getToken } from './auth';
import _ from 'lodash';
import {
  ACE_TOOL
} from '../services/constant';
/**
 * 统一日志处理
 */
const { info, warn, error, time, timeEnd } = console;
export const debug = {
  info,
  warn,
  error,
  time,
  timeEnd
};

/**
 * 设置cookie
 */
export function setCookie(name: string, value: any, exdays: number) {
  const d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  const expires = d.toUTCString();
  document.cookie = `${name}=${value};expires=${expires};path=/`;
}

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * 获取制定名称的cookie的值
 */
export function getCookie(name: string) {
  const cookieReg = new RegExp(`(^|)${name}=([^;]*)(;|$)`);
  const arr = document.cookie.match(cookieReg);
  if (arr && arr.length > 1) {
    return unescape(arr[2]);
  }
  return null;
}

/**
 * 删除制定cookie
 * @param {string} name
 */
export function delCookie(name: string) {
  const exp = new Date();
  exp.setTime(exp.getTime() - 1);
  const cval = getCookie(name);
  if (cval != null) {
    document.cookie = `${name}=${cval};expires=${exp.toUTCString()};path=/`;
  }
}

/**
 * 转换为千分位
 * @param {Number} num
 */
export function toThousands(num: number) {
  return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}

export const getFileUploadUrl = (): string => {
  return `${ACE_TOOL}/oss/upload`;
};
export const getFileDownLoadUrl = (backEndId?: string): string => {
  if (!backEndId) return '';
  return `${ACE_TOOL}/oss/download?fileId=${backEndId}&Authorization=${getToken()}`;
};

/**
 * 获取url的参数
 * @param name 参数名
 */
export const GetParam = (name: string, url?: string, decode?: boolean) => {
  const search = url ? url : window.location.href;
  const pattern = new RegExp('[?&]' + name + '=([^&]+)', 'g');
  const matcher = pattern.exec(search);
  let items = '';
  if (matcher != null) {
    try {
      items = decode
        ? decodeURIComponent(decodeURIComponent(matcher[1]))
        : matcher[1];
    } catch (e) {
      try {
        items = decode ? decodeURIComponent(matcher[1]) : matcher[1];
      } catch (ee) {
        items = matcher[1];
      }
    }
  }
  return items;
};

export const isEmptyExecptZero = (value: any) => {
  if (value === 0) return false;
  return !value;
};

export const transformBinaryDigit = (limit: number) => {
  let size = '';
  if (limit < 0.1 * 1024) {
    //小于0.1KB，则转化成B
    size = limit.toFixed(2) + 'B';
  } else if (limit < 0.1 * 1024 * 1024) {
    //小于0.1MB，则转化成KB
    size = (limit / 1024).toFixed(2) + 'KB';
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {
    //小于0.1GB，则转化成MB
    size = (limit / (1024 * 1024)).toFixed(2) + 'MB';
  } else {
    //其他转化成GB
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
  }

  const sizeStr = size + ''; //转成字符串
  const index = sizeStr.indexOf('.'); //获取小数点处的索引
  const dou = sizeStr.substr(index + 1, 2); //获取小数点后两位的值
  if (dou == '00') {
    //判断后两位是否为00，如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
  }
  return size;
};



export const parseTextValue = (value: any) => {
  if (
    _.isString(value) &&
    (value.indexOf('[') > -1 || value.indexOf('{') > -1)
  ) {
    try {
      value = JSON.parse(value);
    } catch (err) {
      console.error('parseTextValue fail');
    }
  }

  // 如果是对象
  if (_.isPlainObject(value)) {
    return value.value;
  } else if (_.isArray(value)) {
    // 如果是对象数组
    const tmp = value.map((el: any) => {
      if (_.isObject(el)) {
        return el.value;
      }
      return el;
    });
    value = tmp.join(';');
  }
  return value;
};
/**
 * 数字金额转中文大写
 */
export const moneyCapitalize = (moneys: string) => {
  //汉字的数字
  const cnNums = [
    '零',
    '壹',
    '贰',
    '叁',
    '肆',
    '伍',
    '陆',
    '柒',
    '捌',
    '玖'
  ];
  //基本单位
  const cnIntRadice = ['', '拾', '佰', '仟'];
  //对应整数部分扩展单位
  const cnIntUnits = ['', '万', '亿', '兆'];
  //对应小数部分单位
  const cnDecUnits = ['角', '分', '毫', '厘'];
  //整数金额时后面跟的字符
  const cnInteger = '整';
  //整型完以后的单位
  const cnIntLast = '元';
  //最大处理的数字
  const maxNum = 999999999999999.9999;
  //金额整数部分
  let integerNum;
  //金额小数部分
  let decimalNum;
  //输出的中文金额字符串
  let chineseStr = '';
  //分离金额后用的数组，预定义
  let parts;
  if (moneys == '') {
    return '';
  }
  const money = parseFloat(moneys);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  const money1 = money.toString();
  if (money1.indexOf('.') == -1) {
    integerNum = money1;
    decimalNum = '';
  } else {
    parts = money1.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    let zeroCount = 0;
    const IntLen = integerNum.length;
    for (let i = 0; i < IntLen; i++) {
      const n = integerNum.substr(i, 1);
      const p = IntLen - i - 1;
      const q = p / 4;
      const m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    const decLen = decimalNum.length;
    for (let i = 0; i < decLen; i++) {
      const n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
};